#import "AllinLXRSAUtil.h"
#import "AllinRSAUtil.h"
#import "AllinHexUtil.h"
#import "AllinBase64Util.h"
#define kRSAPublicKey @"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC+JONy3BsyljOmoBSnwCeXkV48Nj3W7hGTd71kUym35kRrSnGsX4eOvIcMbYv9PAa5LmxukzkLNBkqep5DCAAJF2FHP6wswKaKgosliajLcpwZFh6OJ/TA883pcB+v5I0rZZR3mQcq+mo/LXvb74ttdCnC0RWj5fcjRn1Xs6xpZwIDAQAB"
#define kMAXENCRYPTBLOCK    117
@implementation AllinLXRSAUtil

//返回16进制数据
+ (NSString*)rsaEncrypt:(NSString*)oriStr{
    //①自己的转换操作
    NSData *data = [AllinLXRSAUtil conversePass:oriStr];
    //②RSA加密
    NSData *retData = [AllinRSAUtil encryptData:data publicKey:kRSAPublicKey padding:kSecPaddingPKCS1];
    //③HEX输出
    NSString* retStr = [AllinHexUtil  encode:retData];
    return retStr;
}

+ (NSData*)conversePass:(NSString*)oriStr{
    NSString *s = [AllinHexUtil encode:[oriStr dataUsingEncoding:NSUTF8StringEncoding]];
    NSUInteger length = s.length/2;/*中文一个3字节，所以转成16进制后除以2才是真正的长度*/
    
    NSString *tenLength = [AllinHexUtil hexFromInt:(length/10 + 48)];
    NSString *digLength = [AllinHexUtil hexFromInt:(length%10 + 48)];
    NSString *targetEncode = [NSString stringWithFormat:@"%@%@%@",tenLength,digLength,s];
    
    if ((length + 2) > kMAXENCRYPTBLOCK) {
        NSLog(@"加密内容太长");
        return nil;
    }
    
    NSMutableData *tmpData = [NSMutableData data];
    for (int i = 0; i < (length + 2); i++) {
        Byte tmpByte = (Byte)strtoul([[targetEncode substringWithRange:NSMakeRange(i*2, 2)] UTF8String],0,16);
        [tmpData appendBytes:&tmpByte length:1];
    }
    for (NSInteger i = tmpData.length; i < kMAXENCRYPTBLOCK; i++) {
        Byte tmpByte = (Byte)(arc4random()*10%10);
        [tmpData appendBytes:&tmpByte length:1];
    }
    return [tmpData copy];
}

@end
